package com.zbcz.erp.adapter

import android.util.Log
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.launcher.ARouter
import com.zbcz.erp.R
import com.zbcz.erp.bean.MyToolsBean
import com.zbcz.erp.databinding.ItemMyApplyBinding
import com.zbcz.erp.util.onSingleClick

class MyApplyToolsAdapter :
    ListAdapter<MyToolsBean, MyApplyToolsAdapter.MyApplyHolder>(DiffCallback()) {

    companion object {
        const val TAG = "MyApplyToolsAdapter"
        const val MY_TOOLS_BEAN = "MyToolsBean"
        fun extractAfterSecondLastSlash(input: String?): String? {
            // 找到倒数第二个 '/' 的索引
            val secondLastSlashIndex = input?.lastIndexOf('/', input.lastIndexOf('/') - 1)
            // 提取从倒数第二个 '/' 到结尾的部分
            return secondLastSlashIndex?.let { input?.substring(it) }
        }
    }

    class DiffCallback : DiffUtil.ItemCallback<MyToolsBean>() {
        override fun areItemsTheSame(oldItem: MyToolsBean, newItem: MyToolsBean): Boolean {
            return oldItem.id == newItem.id
        }

        override fun areContentsTheSame(oldItem: MyToolsBean, newItem: MyToolsBean): Boolean {
            return oldItem == newItem
        }

    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyApplyHolder {
        val binding = ItemMyApplyBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        return MyApplyHolder(binding)
    }

    override fun onBindViewHolder(holder: MyApplyHolder, position: Int) {
        holder.bind(getItem(position))

    }

    inner class MyApplyHolder(private val binding: ItemMyApplyBinding) :
        RecyclerView.ViewHolder(binding.root) {

        init {

            binding.root.onSingleClick {
                Log.i(TAG, currentList[adapterPosition].toString())
                val routeUrl = extractAfterSecondLastSlash(currentList[adapterPosition].routeName)
                if (routeUrl != null) {
                    ARouter.getInstance().build(routeUrl)
                        .withParcelable(MY_TOOLS_BEAN, currentList[adapterPosition]).navigation()
                }
            }
        }

        fun bind(item: MyToolsBean) {
            binding.tvTitle.text = item.description
//            val mBackRes = when (item.id) {
//                R.id.travel_reimbursement_form, R.id.business_trip_form -> R.drawable.plane_icon
//                R.id.reimbursement_form -> R.drawable.business_trio_icon
//                else -> R.drawable.default_icon
//            }
            binding.ivIcon.setImageResource(R.drawable.default_icon)
        }
    }
}